package com.victor.modular.system.service;

import com.victor.common.constant.cache.Cache;
import com.victor.common.persistence.dao.MenuMapper;
import com.victor.common.persistence.dao.RelationMapper;
import com.victor.common.persistence.dao.RoleMapper;
import com.victor.common.persistence.dao.UserMapper;
import com.victor.config.properties.VictorProperties;
import com.victor.core.cache.CacheKit;
import com.victor.core.util.RedisClient;
import com.victor.modular.system.dao.MenuDao;
import com.victor.modular.system.dao.RoleDao;
import com.victor.modular.system.dao.UserMgrDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.Set;

/**
 * 公共的Service
 */
@Service
public class BaseService {
    protected final static Logger logger = LoggerFactory.getLogger(BaseService.class);
    @Resource
    protected RedisClient redisClient;

    /*模板*/
    @Resource
    protected VictorProperties victorProperties;
    protected static ThreadLocal<SimpleDateFormat> tl = new ThreadLocal<SimpleDateFormat>();

    /*用户*/
    @Resource
    protected UserMapper userMapper;
    @Resource
    protected UserMgrDao userMgrDao;

    /*角色*/
    @Resource
    protected RoleMapper roleMapper;
    @Resource
    protected RoleDao roleDao;
    @Resource
    protected RelationMapper relationMapper;//角色和菜单关联表

    /*菜单*/
    @Resource
    protected MenuMapper menuMapper;
    @Resource
    protected MenuDao menuDao;


    /**
     * @Auther:Victor
     * @Description:清楚缓存
     * @Date:Create in 14:10 2018/4/11
     * @Modified By:
     */
    protected void clearCache(String key) {
        CacheKit.remove(Cache.CONSTANT, key);
        try {
            //logger.info("移除缓存KEY：" + key);
            redisClient.del(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Auther:Victor
     * @Description:移除所有缓存
     * @Date:Create in 10:43 2018/5/18
     * @Modified By:
     */
    protected void clearAllCache() throws Exception {
        CacheKit.removeAll(Cache.CONSTANT);
        String key = Cache.CONSTANT + "~keys";
        Set<String> set = redisClient.zrange(key, 0, -1);
        //logger.info("Ehcache缓存数量：" + set.size());
        for (Iterator<String> it = set.iterator(); it.hasNext(); ) {
            String next = it.next();
            redisClient.del(next);
          //  logger.info("移除Ehcache缓存：" + next);
        }
        long count = redisClient.zremrangeByRank(key, 0, -1);
        //logger.info("清空Ehcache缓存：" + count);
    }

}